package com.zidongxiangxi.sharding.job.core;

import com.zidongxiangxi.sharding.job.core.registry.ZookeeperRegistryCenter;
import com.zidongxiangxi.sharding.job.core.util.IpUtils;

import java.lang.management.ManagementFactory;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 分片任务注册
 * FIXME 这个类似乎有点多余，实际上只是提供了获取本地实例id的能力，可以考虑变成一个工具类
 *
 * @author chenxudong
 * @date 2021/02/18
 */
public class ShardingJobRegistry {
    private static final String DELIMITER = "@-@";

    private static volatile ShardingJobRegistry instance;

    private final Map<String, ZookeeperRegistryCenter> regCenterMap = new ConcurrentHashMap<>();

    private final String instanceId;

    private ShardingJobRegistry() {
        instanceId = IpUtils.getIp() + DELIMITER + ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
    }

    /**
     * 获取自己的实例
     *
     * @return 自己的实例
     */
    public static ShardingJobRegistry getInstance() {
        if (null == instance) {
            synchronized (ShardingJobRegistry.class) {
                if (null == instance) {
                    instance = new ShardingJobRegistry();
                }
            }
        }
        return instance;
    }

    /**
     * 获取本地实例的id
     *
     * @return 本地实例的id
     */
    public String getLocalInstanceId() {
        return instanceId;
    }

    public void registerRegistryCenter(final String jobName, final ZookeeperRegistryCenter regCenter) {
        regCenterMap.put(jobName, regCenter);
        regCenter.addCacheData("/" + jobName);
    }

    public void shutdown(String jobName) {
        regCenterMap.remove(jobName);
    }

    public boolean isShutdown(String jobName) {
        return !regCenterMap.containsKey(jobName);
    }
}
